#!/usr/bin/perl -w
use warnings;
use IO::Socket;
use Net::hostent;
use File::stat;
use XML::Simple;
use Data::Dumper;
use File::Basename;
use Switch;

$config = readConfig();

$server = IO::Socket::INET->new( Proto     => 'tcp',
                          LocalPort => $config->{'server-port'}->{'content'},
                          Listen    => SOMAXCONN,
                          Reuse     => 1);

$server_root = $config->{'server-root'}->{'content'};
							  
die "Server failed.\n" unless $server;
print "Server is up and running.\n\n";

while ($client = $server->accept()) 
{
	$client->autoflush(1);

	$request = <$client>;

	logMsg($request);

	if($request =~ m|^GET /(.+) HTTP/1.| || $request =~ m|^GET / HTTP/1.|)
	{
		if ($1 && -e $server_root.'www/'.$1)
		{
			$filename = $server_root.'www/'.$1;
		}
		elsif($1 && $1 eq "" && -e "index.html")
		{
			$filename = $server_root.'www/index.html';
		}
		else
		{
			$filename = $server_root.'errors/404.html';
			logErr("Not found - ".$request);
		}

		my(undef, undef, $ftype) = fileparse($filename,qr/\.[^.]*/);

		$filesize = stat($filename)->size;

		switch (lc $ftype) {
			case ".jpg"	{ $content_type = "image/jpg"; }
			case ".jpeg"	{ $content_type = "image/jpg"; }
			case ".png"	{ $content_type = "image/png"; }
			else		{ $content_type = "text/html"; }
		}  

		print $client "HTTP/1.0 200 OK\nContent-Type: $content_type; charset=utf-8\nContent-Length: $filesize\nServer: ".$config->{'server-sig'}->{'content'}."\n\n";

		open(my $f,"<$filename");
		while(<$f>) { print $client $_ };

	}
	else
	{
		logErr("Bad request - ".$request);
		print $client '<h2>Bad request!</h2>';
	}

	close $client;    
}

sub logMsg
{
	open(LOGFILE,">>logs/access.log") || die("Unable to open: access.log\n");
	print LOGFILE @_;
	close(LOGFILE);
}
sub logErr
{
	open(LOGFILE,">>logs/error.log") || die("Unable to open: access.log\n");
	print LOGFILE @_;
	close(LOGFILE);
}

sub readConfig
{
	my $file = 'config/config.xml';
	my $xs1 = XML::Simple->new();

	my $doc = $xs1->XMLin($file);

	my $config = $doc->{'item'};
	return $config;
}

